package main

// cd /data/release/ginfwk/server/devops/server
// go build -o devops-hooks ./main.go
// nohup ./devops-hooks &

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"os/exec"
	"time"
)

type Response struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

func buildServer() (res error) {
	defer func() {
		if err := recover(); err != nil {
			res = err.(error)
		}
	}()

	// 先拉取代码
	if msg, err := exec.Command("/usr/bin/cd", "/data/release/ginfwk").CombinedOutput(); err != nil {
		return fmt.Errorf("cd ginfwk failed, err:%s msg:%s", err, msg)
	}

	if msg, err := exec.Command("/usr/bin/git", "pull").CombinedOutput(); err != nil {
		return fmt.Errorf("git pull ginfwk failed, err:%s msg:%s", err, msg)
	}

	// 开始构建

	// 启动build-kit
	// if _, err := exec.Command("/usr/local/bin/buildkitd", "--config /etc/buildkit/buildkitd.toml > /dev/null 2>&1 &").CombinedOutput(); err != nil {
	//     log.Println("buildkitd start new instance failed, skip.")
	// }

	// 进入项目主目录
	projectHome := "/data/release/ginfwk"
	if msg, err := exec.Command("/usr/bin/cd", projectHome).CombinedOutput(); err != nil {
		return fmt.Errorf("cd ginfwk failed, err:%s msg:%s", err, msg)
	}

	// 构建镜像
	if msg, err := exec.Command(
		"/usr/local/bin/buildctl",
		"build",
		"--local", "context="+projectHome,
		"--local", "dockerfile="+projectHome+"/server/k8s/deploy/.", // docker-file
		"--frontend=dockerfile.v0",
		"--opt", "platform=linux/amd64",
		"--export-cache", "type=inline",
		"--output", "type=image,name=docker.io/llqhz/go-server:v1.0.0",
	).CombinedOutput(); err != nil {
		return fmt.Errorf("buildctl build failed, err:%s msg:%s", err, msg)
	}
	// 部署镜像
	if msg, err := exec.Command("/usr/local/bin/kubectl", "apply", "-f", projectHome+"/server/k8s/deploy/server-delete.yaml").CombinedOutput(); err != nil {
		return fmt.Errorf("kubectl delete failed, err:%s msg:%s", err, msg)
	}
	if msg, err := exec.Command("/usr/local/bin/kubectl", "apply", "-f", projectHome+"/server/k8s/deploy/server-deploy.yaml").CombinedOutput(); err != nil {
		return fmt.Errorf("kubectl deploy failed, err:%s msg:%s", err, msg)
	}
	// 返回成功
	return nil
}

// gitee web-hooks 构建触发
func main() {

	http.HandleFunc("/devops/ginfwk", func(response http.ResponseWriter, request *http.Request) {
		res := Response{
			Code: 0,
			Msg:  "ok",
			Data: nil,
		}
		timeStart := time.Now()
		if err := buildServer(); err != nil {
			res.Code = -1
			res.Msg = err.Error()
		} else {
			timeEnd := time.Now()
			timeSpend := float64(timeEnd.Sub(timeStart).Milliseconds()) / 1000.0

			res.Data = map[string]interface{}{
				"timeStart": timeStart,
				"timeEnd":   timeEnd,
				"timeSpend": fmt.Sprintf("%.3fs", timeSpend),
			}
		}

		// 处理请求
		bts, _ := json.Marshal(res)
		response.Header().Add("Status", "ok")
		response.WriteHeader(http.StatusOK)
		if _, err := response.Write(bts); err != nil {
			return
		}
	})

	if err := http.ListenAndServe("0.0.0.0:8111", nil); err != nil {
		log.Fatalf("http server run failed, err: %s\n", err)
	}
	log.Println("http server stopped success, finished.")
}
